package com.lboyang.remoting.transport.netty.client;

import com.lboyang.common.constants.NrpcConstants;
import com.lboyang.common.dto.NrpcMessage;
import com.lboyang.common.dto.NrpcRequest;
import com.lboyang.common.dto.NrpcResponse;
import com.lboyang.common.enums.CompressTypeEnum;
import com.lboyang.common.enums.SerializationTypeEnum;
import com.lboyang.common.extension.ExtensionLoader;
import com.lboyang.common.factory.SingletonFactory;
import com.lboyang.provider.registry.ServiceDiscovery;
import com.lboyang.remoting.transport.NrpcRequestTransport;
import com.lboyang.remoting.transport.netty.codec.RpcMessageDecoder;
import com.lboyang.remoting.transport.netty.codec.RpcMessageEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @Description：
 *      Netty 的客户端，用于发送序列化后请求调用服务，并接收响应进行解码
 * @Date 2021/9/11 22:39
 * @author: A.iguodala
 */
@Slf4j
public class NettyRpcClient implements NrpcRequestTransport {

    /**
     * 服务发现
     */
    private final ServiceDiscovery serviceDiscovery;

    /**
     * 未处理的请求
     */
    private final UnprocessedRequests unprocessedRequests;

    /**
     * 通道提供
     */
    private final ChannelProvider channelProvider;

    /**
     * Netty 客户端启动引导器
     */
    private final Bootstrap bootstrap;

    /**
     * 事件线程组
     */
    private final EventLoopGroup eventLoopGroup;

    public NettyRpcClient() {
        // 创建客户端线程组
        eventLoopGroup = new NioEventLoopGroup();
        // 创建 Netty 启动引导器
        bootstrap = new Bootstrap();
        // 设置启动参数
        // 使用的线程组
        bootstrap.group(eventLoopGroup)
                // 管道类型
                .channel(NioSocketChannel.class)
                // 选项字段，超过5s没建立连接则连接失败
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                // 日志打印处理器
                .handler(new LoggingHandler(LogLevel.INFO))
                // 初始化管道
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline p = socketChannel.pipeline();
                        // 五秒没有向服务器发送消息就进行心跳检测
                        p.addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
                        // pipline 中添加RPC消息的编码器
                        p.addLast(new RpcMessageEncoder());
                        // 添加解码器
                        p.addLast(new RpcMessageDecoder());
                        // 添加客户端的处理器
                        p.addLast(new NettyRpcClientHandler());
                    }
                });
        this.serviceDiscovery = ExtensionLoader.getExtensionLoader(ServiceDiscovery.class).getExtension("registrationCenter");
        this.unprocessedRequests = SingletonFactory.getInstance(UnprocessedRequests.class);
        this.channelProvider = SingletonFactory.getInstance(ChannelProvider.class);
    }

    /**
     * 发送 RPC 封装的请求
     * @param rpcRequest
     * @return
     */
    @Override
    public Object sendRpcRequest(NrpcRequest rpcRequest) {
        // 创建请求返回异步任务
        CompletableFuture<NrpcResponse<Object>> resultFuture = new CompletableFuture<>();
        // 获取服务具体地址
        InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(rpcRequest);
        // 获取该地址的通道
        Channel channel = getChannel(inetSocketAddress);
        if (channel.isActive()) {
            // 将请求放到对应的处理池中
            unprocessedRequests.put(rpcRequest.getRequestId(), resultFuture);
            // 构造 RPC 信息
            NrpcMessage rpcMessage = NrpcMessage.builder().data(rpcRequest)
                    .codec(SerializationTypeEnum.PROTOSTUFF.getCode())
                    .compress(CompressTypeEnum.GZIP.getCode())
                    .messageType(NrpcConstants.REQUEST_TYPE).build();
            // 发送信息并注册监听异步调用
            channel.writeAndFlush(rpcMessage).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    log.info("client send message: [{}]", rpcMessage);
                } else {
                    future.channel().close();
                    resultFuture.completeExceptionally(future.cause());
                    log.error("Send failed:", future.cause());
                }
            });
        } else {
            throw new IllegalStateException();
        }
        return resultFuture;
    }


    /**
     * 获取对应服务地址的通道
     * @param inetSocketAddress
     * @return
     */
    public Channel getChannel(InetSocketAddress inetSocketAddress) {
        Channel channel = channelProvider.get(inetSocketAddress);
        if (channel == null) {
            channel = doConnect(inetSocketAddress);
            channelProvider.set(inetSocketAddress, channel);
        }
        return channel;
    }

    @SneakyThrows
    public Channel doConnect(InetSocketAddress inetSocketAddress) {
        CompletableFuture<Channel> completableFuture = new CompletableFuture<>();
        bootstrap.connect(inetSocketAddress).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("The client has connected [{}] successful!", inetSocketAddress.toString());
                completableFuture.complete(future.channel());
            } else {
                throw new IllegalStateException();
            }
        });
        return completableFuture.get();
    }


    /**
     * 优雅关闭客户端线程组
     */
    public void close() {
        eventLoopGroup.shutdownGracefully();
    }
}
